package com.gongren.open.rpc.service.rpc;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dlg.commons.exception.DataSaveException;
import com.dlg.commons.util.Utils;
import com.gongren.open.rpc.service.dao.mappers.ActivitySignUpMapper;
import com.gongren.open.rpc.service.domain.ActivitySignUp;
import com.gongren.open.rpc.service.redis.CacheService;
import com.gongren.open.rpc.service.redis.RedisKeyConstants;
import com.gongren.project.commons.enums.SourceEnum;
import com.gongren.project.commons.service.sms.api.service.ISmsRpcService;
import com.gongren.project.commons.enums.VerifyCodeEnum;
import com.gongren.project.commons.service.ocr.rpc.api.IdCardRpcService;
import com.gongren.project.commons.service.ocr.rpc.api.vo.ValidateIdCardRpcVo;
import com.gongren.project.commons.service.sms.api.vo.VerifyCodeRpcVo;
import com.gongren.project.odd.job.rpc.api.vo.Activity.ActivityRpcVo;
import com.gongren.project.open.rpc.api.IActivityRpcService;
import com.gongren.project.open.rpc.api.vo.ActivitySignUpRpcVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.groups.ConvertGroup;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zhangjinxia on 2017/9/6.
 */
@Service(version = "0.0.1")
public class ActivitySignUpRpcServiceImpl implements IActivityRpcService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ActivitySignUpMapper activitySignUpMapper;

    @Autowired
    private CacheService cacheService;

    @Reference(version = "0.0.1")
    private IdCardRpcService idCardRpcService;

    @Reference(version = "0.0.1")
    private ISmsRpcService smsRpcService;

    @Reference(version = "0.0.1")
    private com.gongren.project.odd.job.rpc.api.service.activity.IActivityRpcService activityRpcService;

    @Override
    public BigInteger saveActivitySignUp(ActivitySignUpRpcVo activitySignUpRpcVo) {
        logger.info("活动注册dubbo服务调用开始");
        logger.info("参数："+ JSON.toJSONString(activitySignUpRpcVo));
        String validMsg = activitySignUpRpcVo.validate();
        if (validMsg!=null){
            throw new RuntimeException(validMsg);
        }
        if (!cacheService.existsKey(RedisKeyConstants.ACTIVITY_REGISTER_CANAL.concat(activitySignUpRpcVo.getCanalNumber()))){
            throw new RuntimeException("渠道号不存在");
        }
        if (cacheService.existsKey(RedisKeyConstants.ACTIVITY_REGISTER_PHONE.concat(activitySignUpRpcVo.getTel()))){
            throw new RuntimeException("手机号已存在");
        }
        if (cacheService.existsKey(RedisKeyConstants.ACTIVITY_REGISTER_IDCARD.concat(activitySignUpRpcVo.getIdcard()))){
            throw new RuntimeException("身份证号已存在");
        }
        logger.info("活动注册校验验证码是否正确开始，手机号:"+activitySignUpRpcVo.getTel()+"，验证码："+activitySignUpRpcVo.getVaildCode());
        VerifyCodeRpcVo verifyCodeVo = new VerifyCodeRpcVo();
        verifyCodeVo.setPhone(activitySignUpRpcVo.getTel());
        verifyCodeVo.setVerifyCode(activitySignUpRpcVo.getVaildCode());
        verifyCodeVo.setSource(SourceEnum.ODD_JOB);
        VerifyCodeEnum verifyCodeEnum = smsRpcService.checkCodeNoDelete(verifyCodeVo);
        if (null == verifyCodeEnum || VerifyCodeEnum.SUCCESS != verifyCodeEnum) {
            logger.info("活动注册校验验证码是否正确结束，返回消息："+verifyCodeEnum.getValue());
            throw new RuntimeException("验证码校验不通过");
        }
        //姓名和身份证号
        logger.info("活动注册校验身份证号和姓名是否匹配开始，身份证:"+activitySignUpRpcVo.getIdcard()+",姓名："+activitySignUpRpcVo.getName());
        ValidateIdCardRpcVo validateIdCardRpcVo = idCardRpcService.validateIdCard(activitySignUpRpcVo.getName(), activitySignUpRpcVo.getIdcard());
        logger.info("活动注册校验身份证号和姓名是否匹配结束，返回消息：",validateIdCardRpcVo.getMessage());
        if (!"1".equals(validateIdCardRpcVo.getResult())) {
            throw new RuntimeException("证件姓名和号码不匹配！");
        }
        activitySignUpRpcVo.setId(Utils.id());
        ActivitySignUp activitySignUp = new ActivitySignUp();
        Utils.copyNotNullObject(activitySignUpRpcVo, activitySignUp);
        cacheService.putObject(RedisKeyConstants.ACTIVITY_REGISTER_PHONE.concat(activitySignUpRpcVo.getTel()), activitySignUp);
        cacheService.putObject(RedisKeyConstants.ACTIVITY_REGISTER_IDCARD.concat(activitySignUpRpcVo.getIdcard()), activitySignUp);
        activitySignUpMapper.save(activitySignUp);
        logger.info("活动注册dubbo服务调用结束");
        return activitySignUpRpcVo.getId();
    }

    @Override
    public List<ActivityRpcVo> list(Integer userType, Integer showType) {
        List<ActivityRpcVo> vos = new ArrayList<>();
        if (userType==null){
            userType = 3;
        }
        String cacheKey = RedisKeyConstants.ACTIVITY_PEACOCK.concat(showType.toString());
        if (cacheService.existsKey(cacheKey)){
            List<JSONObject> list = cacheService.getObject(cacheKey, List.class);
            for (JSONObject h:list){
                ActivityRpcVo activityRpcVo = new ActivityRpcVo();
                activityRpcVo.setContent(h.get("content")==null ? "" : h.get("content").toString());
                activityRpcVo.setUrl(h.get("url")==null ? "" : h.get("url").toString());
                activityRpcVo.setCountDownSec(h.get("countDownSec")==null ? 0 : new Integer(h.get("countDownSec").toString()));
                activityRpcVo.setTitile(h.get("titile")==null ? "" : h.get("titile").toString());
                activityRpcVo.setImageUrl(h.get("imageUrl")==null ? "" : h.get("imageUrl").toString());
                activityRpcVo.setShowType(h.get("active")==null ? null : new Short(h.get("active").toString()));
                activityRpcVo.setStartTime(h.get("startTime")==null ? null : new Date((Long)h.get("startTime")));
                activityRpcVo.setEndTime(h.get("endTime")==null ? null : new Date((Long)h.get("endTime")));
                activityRpcVo.setId(h.get("id")==null ? null : new BigInteger(h.get("id").toString()));
                activityRpcVo.setSn(h.get("sn")==null ? "" : h.get("sn").toString());
                activityRpcVo.setUserType(h.get("userType")==null ? null : new Short(h.get("userType").toString()));
                activityRpcVo.setIsUpdate(h.get("isUpdate")==null ? null : new Integer(h.get("isUpdate").toString()));
                vos.add(activityRpcVo);
            }
        }else {
            vos = activityRpcService.list(userType, showType);
            cacheService.putObject(cacheKey, vos);
        }

        return vos;
    }
}
